package com.wjk.cms.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class PaysignUtil {

    public static byte[] tripleDesEncrypt(byte[] content, byte[] key) throws Exception {
        byte[] icv = new byte[8];
        System.arraycopy(key, 0, icv, 0, 8);
        return tripleDesEncrypt(content, key, icv);
    }

    protected static byte[] tripleDesEncrypt(byte[] content, byte[] key, byte[] icv) throws Exception {
        final SecretKey secretKey = new SecretKeySpec(key, "DESede");
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        final IvParameterSpec iv = new IvParameterSpec(icv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return cipher.doFinal(content);
    }

    public static byte[] tripleDesDecrypt(byte[] content, byte[] key) throws Exception {
        byte[] icv = new byte[8];
        System.arraycopy(key, 0, icv, 0, 8);
        return tripleDesDecrypt(content, key, icv);
    }

    protected static byte[] tripleDesDecrypt(byte[] content, byte[] key, byte[] icv) throws Exception {
        final SecretKey secretKey = new SecretKeySpec(key, "DESede");
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        final IvParameterSpec iv = new IvParameterSpec(icv);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return cipher.doFinal(content);
    }

    public static void main(String[] args) throws Exception {
        //byte[] content = "{\"order_id\": \"201609010016562012978\",\"dealer_id\":\"25479280\",\"broker_id\": \"27532644\",\"real_name\": \"张邦超\",\"card_no\":\"6222802349231001277\",\"phone_no\": \"13513186685\",\"id_card\":\"372928199004121355\",\"pay\": \"31.2\",\"notify_url\":\"http://syz2xh.natappfree.cc/oauth2/hlt/orderStatus\"}".getBytes("utf-8");
        byte[] content = "{\"card_no\": \"6222802349231001277\",\"id_card\":\"372928199004121355\",\"real_name\": \"张邦超\"}".getBytes("utf-8");
        byte[] key = "t9RLg0IX0FlnVR9Dc5iL4gU7".getBytes("utf-8");
        byte[] enc = PaysignUtil.tripleDesEncrypt(content, key);
        byte[] enc64 = Base64.encodeBase64(enc);
        System.out.println("encrypt: " + new String(enc64));
        byte[] dec64 = Base64.decodeBase64(enc64);
        byte[] dec = PaysignUtil.tripleDesDecrypt(dec64, key);

        String str = new String(dec);
        System.out.println("decrypt: " + str);
    }

}
